package com.hyt.it.ogt.kq.service.gov.arrange;

import com.hyt.core.util.UUIDUtils;
import com.hyt.it.ogt.kq.common.config.exception.KqException;
import com.hyt.it.ogt.kq.common.gov.constant.ResponseCode;
import com.hyt.it.ogt.kq.service.gov.arrange.model.Proctor;
import com.hyt.it.ogt.kq.service.gov.arrange.model.Room;
import com.hyt.it.ogt.kq.service.gov.model.entity.TimeExaminer;
import com.hyt.it.ogt.kq.service.gov.model.entity.TimeRoomExaminer;
import com.hyt.it.ogt.kq.service.gov.model.param.proctor.AutoProctorParam;
import com.hyt.progress.service.ProgressManager;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedDeque;


@Service
public class ProctorArrangeByRandomAdapter extends ProctorArrangeAbstractService {
    public static final String DEFAULT = "default";

    @Override
    public void arrange(AutoProctorParam param) {
        ProgressManager.updateProgress(5L);
        // 监考老师数量
        int teacherNum = this.getTeacherNum(param);
        ProgressManager.updateProgress(23L);

        // 获取所有监考员，不分级别
        Map<String, ConcurrentLinkedDeque<Proctor>> proctorMap = this.getProctorList(param.getTaskId());
        ProgressManager.updateProgress(35L);

        if (proctorMap.isEmpty()) {
            throw new KqException(ResponseCode.PROCTOR_ARRANGE_NOT_MATCH.getCode(), ResponseCode.PROCTOR_ARRANGE_NOT_MATCH.getMsg());
        }

        // 获取所有考场
        List<Room> dataList = timeRoomCandidateMapper.getProctorArrangeRoomList(param.getTaskId());
        ProgressManager.updateProgress(55L);

        List<TimeExaminer> timeExaminerList = new ArrayList<>();
        Map<String, String> timeExaminerMap = new HashMap<>();

        List<TimeRoomExaminer> timeRoomExaminerList = new ArrayList<>();

        for (Room e : dataList) {
            // 所有考场都是默认一个组，与监考员一样的组
            ConcurrentLinkedDeque<Proctor> proctors = proctorMap.get(DEFAULT);
            if (CollectionUtils.isEmpty(proctors)) {
                break;
            }

            // 先从监考员列表里面拿出多个监考员，绑定到该考场，不管考场考多少个批次，保证同一考场不同批次绑定同样的监考员
            List<Proctor> tmpProctorList = new ArrayList<>();
            for (int i = 0; i < teacherNum; i++) {
                if (CollectionUtils.isEmpty(proctors)) {
                    break;
                }
                tmpProctorList.add(proctors.pop());
            }

            String[] times = e.getTimeIdStr().split(",");
            // 循环考场需要考的批次
            for (String time : times) {
                // 同一考场不同批次，使用同样的监考员
                for (Proctor proctor : tmpProctorList) {
                    String timeKey = e.getRoomId() + "_" + time;
                    String timeExaminerId = timeExaminerMap.get(timeKey);
                    if (!timeExaminerMap.containsKey(timeKey)) {
                        TimeExaminer timeExaminer = new TimeExaminer();
                        timeExaminer.setExaminerId(proctor.getExaminerId()).setTimeId(time).setUserId(proctor.getUserId()).setTaskId(param.getTaskId()).setId(UUIDUtils.randomUUID());
                        timeExaminerList.add(timeExaminer);
                        timeExaminerMap.put(timeKey, timeExaminer.getId());
                    }
                    timeRoomExaminerList.add(TimeRoomExaminer.builder().timeExaminerId(timeExaminerId).timeId(time)
                            .roomId(e.getRoomId()).userId(proctor.getUserId()).taskId(param.getTaskId()).build());
                }
            }
        }

        ProgressManager.updateProgress(90L);

        if (timeRoomExaminerList.size() > 0) {
            iTimeRoomExaminerService.saveBatch(timeRoomExaminerList, 1000);
            iTimeExaminerService.saveBatch(timeExaminerList, 1000);
            ProgressManager.updateProgress(98L);
        } else {
            throw new KqException(ResponseCode.PROCTOR_ARRANGE_NOT_MATCH.getCode(), ResponseCode.PROCTOR_ARRANGE_NOT_MATCH.getMsg());
        }
    }

    /**
     * 获取所有监考员
     * @param taskId
     * @return
     */
    private Map<String, ConcurrentLinkedDeque<Proctor>> getProctorList(String taskId) {
        Map<String, ConcurrentLinkedDeque<Proctor>> map = new HashMap<>();
        // 获取所有监考员
        List<Proctor> dataList = examinerMapper.getProctorList(taskId);
        for (Proctor p : dataList) {
            // 把所有监考员分到一个默认的组
            ConcurrentLinkedDeque<Proctor> list = map.get(DEFAULT);
            if (list == null) {
                list = new ConcurrentLinkedDeque<>();
                map.put(DEFAULT, list);
            }
            list.add(p);
        }
        return map;
    }

}
